import 'package:dailoz/constants.dart';
import 'package:dailoz/dio/http_util.dart';
import 'package:dailoz/generated/l10n.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:dailoz/size_config.dart';
import 'package:dailoz/utils/TaskUtils.dart';
import 'package:dailoz/utils/input_utils.dart';
import 'package:dailoz/utils/showAlertDialog.dart';
import 'package:dailoz/widgets/progress_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TaskTagDetail extends StatefulWidget {
  const TaskTagDetail({Key? key}) : super(key: key);

  static String id = 'taskTagDetailId';

  @override
  State<TaskTagDetail> createState() => _TaskTagDetailState();
}

class _TaskTagDetailState extends State<TaskTagDetail> {
  String? date;
  bool isLoading = false;
  int? status = 1;

  DateTime now = DateTime.now();
  DateTime? selectedDate = DateTime.now();

  List<Widget>? taskList = [];
  List<String>? statusList = ["completed", "cancel", "pending", "on Going"];

  TextEditingController? searchController;

  getTaskListByTag(DateTime time, String keyword, int statusCode) async {
    taskList = [];
    setState(() {
      isLoading = !isLoading;
    });
    final prefs = await SharedPreferences.getInstance();
    var response = await HttpUtil().get("/task/taskByDate", data: {
      "id": prefs.getString("user-id"),
      "tag": prefs.getString("tag-name"),
      "options": time,
      "keyword": keyword,
      "status": statusCode,
    });
    if (response != null) {
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);

      Map<String, dynamic> map = {};
      map = responseJsonEntity.data;
      List<String> keys = map.keys.toList();
      for (var element in keys) {
        taskList?.add(TaskUtils.generateTaskList(element, map));
      }
    }
    setState(() {
      isLoading = !isLoading;
    });
  }

  @override
  void initState() {
    super.initState();
    getTaskListByTag(now, "", status!);
    DateTime time = DateTime.now();
    date = "${time.year}-${months[time.month - 1]}";
    searchController = TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    searchController?.dispose();
    InputUtil.clear();
  }

  @override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings.arguments;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: ProgressWidget(
        loading: isLoading,
        msg: "正在加载中",
        child: Stack(
          children: [
            Positioned(
              top: SizeConfig.getProportionateScreenHeight(56.0),
              left: SizeConfig.getProportionateScreenWidth(30.0),
              child: Container(
                height: SizeConfig.getProportionateScreenHeight(42.0),
                width: SizeConfig.getProportionateScreenWidth(42.0),
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(
                    Radius.circular(14.0),
                  ),
                ),
                child: IconButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  icon: Icon(
                    Icons.arrow_back_ios_outlined,
                    size: SizeConfig.getProportionateFontSize(14.0),
                  ),
                ),
              ),
            ),
            Center(
              child: SizedBox(
                width: SizeConfig.getProportionateScreenWidth(327.0),
                child: Column(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(
                        top: SizeConfig.getProportionateScreenHeight(60.0),
                      ),
                      child: Container(
                        width: SizeConfig.getProportionateScreenWidth(200.0),
                        alignment: Alignment.center,
                        child: Text(
                          args.toString(),
                          style: TextStyle(
                            fontSize: SizeConfig.getProportionateFontSize(18.0),
                            fontWeight: FontWeight.w500,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                        top: SizeConfig.getProportionateScreenHeight(25.0),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Container(
                              decoration: const BoxDecoration(
                                color: Color(0xffebebeb),
                                borderRadius: BorderRadius.all(
                                  Radius.circular(15.0),
                                ),
                              ),
                              child: TextField(
                                controller: searchController,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  prefixIcon: Icon(
                                    Icons.search_outlined,
                                    color: const Color(0xffbec4d0),
                                    size:
                                        SizeConfig.getProportionateScreenHeight(
                                            20.0),
                                  ),
                                  suffixIcon: IconButton(
                                    icon: Icon(
                                      Icons.highlight_remove_outlined,
                                      color: const Color(0xffbec4d0),
                                      size: SizeConfig
                                          .getProportionateScreenHeight(20.0),
                                    ),
                                    onPressed: () {
                                      searchController!.clear();
                                      getTaskListByTag(selectedDate!,
                                          searchController!.text, status!);
                                    },
                                  ),
                                  hintText: S.of(context).search,
                                  hintStyle: TextStyle(
                                    color: const Color(0xffbec4d0),
                                    fontSize:
                                        SizeConfig.getProportionateFontSize(
                                            14.0),
                                  ),
                                ),
                                onSubmitted: (newValue) {
                                  getTaskListByTag(
                                    now,
                                    searchController!.text,
                                    status!,
                                  );
                                },
                                textAlignVertical: TextAlignVertical.center,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: SizeConfig.getProportionateScreenHeight(45.0),
                      child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: statusList!.length,
                          itemBuilder: (context, index) {
                            return Padding(
                              padding: EdgeInsets.only(
                                top: SizeConfig.getProportionateScreenHeight(
                                    10.0),
                                right: SizeConfig.getProportionateScreenWidth(
                                    15.0),
                                bottom: SizeConfig.getProportionateScreenHeight(
                                    10.0),
                              ),
                              child: GestureDetector(
                                onTap: () {
                                  setState(() {
                                    status = index + 1;
                                    getTaskListByTag(selectedDate!,
                                        searchController!.text, status!);
                                  });
                                },
                                child: Text(
                                  statusList![index],
                                  style: Theme.of(context)
                                      .textTheme
                                      .bodyText2
                                      ?.copyWith(
                                        fontSize:
                                            SizeConfig.getProportionateFontSize(
                                                18.0),
                                        color: index + 1 == status
                                            ? Colors.red
                                            : null,
                                      ),
                                ),
                              ),
                            );
                          }),
                    ),
                    GestureDetector(
                      onTap: () {
                        ShowDialog.showDialog(
                          context,
                          CupertinoDatePicker(
                            mode: CupertinoDatePickerMode.date,
                            initialDateTime: selectedDate,
                            onDateTimeChanged: (newTime) {
                              InputUtil.debounce("sign", () {
                                selectedDate = newTime;
                                date =
                                    "${newTime.year}-${months[newTime.month - 1]}";
                                getTaskListByTag(selectedDate!,
                                    searchController!.text, status!);
                              });
                            },
                          ),
                        );
                      },
                      child: Row(
                        children: [
                          const Icon(
                            Icons.calendar_month_outlined,
                            color: Color(0xff4a5b84),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: Text(
                              date!,
                              style: TextStyle(
                                fontSize:
                                    SizeConfig.getProportionateFontSize(16.0),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: SizeConfig.getProportionateScreenHeight(610.0),
                      child: SingleChildScrollView(
                        child: taskList!.isEmpty
                            ? Center(
                                child: Padding(
                                  padding: EdgeInsets.only(
                                    top:
                                        SizeConfig.getProportionateScreenHeight(
                                            180.0),
                                  ),
                                  child: Text(
                                    S.of(context).noData,
                                    style: TextStyle(
                                      fontSize:
                                          SizeConfig.getProportionateFontSize(
                                              16.0),
                                    ),
                                  ),
                                ),
                              )
                            : Column(
                                children: taskList!,
                              ),
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
